/**
 * 
 */
package com.oscarmovie.action;

import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import tt.util.IOUtils;
import weibo4j.Timeline;
import weibo4j.Users;
import weibo4j.Weibo;
import weibo4j.http.ImageItem;
import weibo4j.model.Status;
import weibo4j.model.User;
import weibo4j.model.WeiboException;
import weibo4j.org.json.JSONObject;
import weibo4j.util.WeiboConfig;

import com.oscarmovie.Constants;
import com.oscarmovie.WeiboUtils;
import com.oscarmovie.model.Account;
import com.oscarmovie.model.Paging;
import com.oscarmovie.model.Video;
import com.oscarmovie.model.WeiboDto;
import com.oscarmovie.service.AccountService;
import com.oscarmovie.service.VideoService;

public class AccountAction implements ServletRequestAware, ServletResponseAware {
	
	private WeiboDto weiboDto;//to carry data for weibo
	
	private Account account;//ONLY for CRUD, NOT for session.
	private HttpSession session;
	private HttpServletRequest request;
	private HttpServletResponse response;
	private AccountService accountService;
	private VideoService videoService;
	private Paging paging = new Paging(20);
	private List<Video> videos;
	
	public String execute() throws Exception{
		Account account = getAccountFromSession();
		if (account!=null){
			listVideos();
			return Constants.SUCCESS;
		} else {
			return Constants.UNAUTH;
		}
	}
	public void save() throws Exception{
		accountService.save(account);
	}
	
	//login-logout/////////////////////////////////////
	public void loginWeibo() throws Exception{
		String url = WeiboConfig.getValue("authorizeURL")
					+"?response_type=token&client_id="+WeiboConfig.getValue("client_ID")
					+"&redirect_uri="+WeiboConfig.getValue("redirect_URI");
		String referer = request.getHeader("referer");
		session.setAttribute("referer", referer);
		response.sendRedirect(url);
	}
	public void login() throws Exception{
		//TODO only support sina weibo at this moment
		Weibo weibo = new Weibo();
		weibo.setToken(weiboDto.getAccessToken());
		weibo4j.Account am = new weibo4j.Account(weibo);
		try {
			JSONObject json = am.getUid();
			String uid = json.getString("uid");
			Users um = new Users(weibo);
			User user = um.showUserById(uid);
			Account accountDB = accountService.loadByWeiboId(user.getId());
			if(accountDB==null){//create
				Account newAccount = new Account();
				newAccount.setWeiboId(user.getId());
				newAccount.setName(user.getName());
				newAccount.setIcon(user.getProfileImageURL().toString());
				newAccount.setLoginCount(1);
				newAccount.setLoginDate(new Date());
				newAccount.setCreateDate(newAccount.getLoginDate());
				accountService.save(newAccount);
			} else {//update
				accountDB.setName(user.getName());
				accountDB.setIcon(user.getProfileImageURL().toString());
				accountDB.setLoginDate(new Date());
				accountDB.setLoginCount(accountDB.getLoginCount()+1);
				
				accountService.save(accountDB);
			}
			
			Account account = accountService.loadByWeiboId(user.getId());
			account.setWeibo(weibo);
			
			session.setAttribute("user",user);
			setAccountToSession(account);
			
			String referer = session.getAttribute("referer")==null?"account":(String)session.getAttribute("referer");
			response.sendRedirect(referer);
		} catch (WeiboException e) {
			System.out.println("Login failed.");
			e.printStackTrace();
			logout();
		}
	}
	
	
	public void logout() throws Exception{
		String referer = request.getHeader("referer")==null?"index":request.getHeader("referer");
		session.invalidate();
		response.sendRedirect(referer);
	}
	
	
	//CRUD/////////////////////////////////////
	public void listVideos(){
		Account account = getAccountFromSession();
		videos = videoService.list(paging, account.getId());
	}
	
	
	//weibo/////////////////////////////////////

	public String updateStatus(){
		Account account = getAccountFromSession();
		Weibo weibo = account.getWeibo();
		Timeline tm = new Timeline(weibo);
		try {
			Status status = tm.UpdateStatus(weiboDto.getStatus());
		} catch (WeiboException e) {
			e.printStackTrace();
		}
		return "weibo";
	}
	
	public String updateStatusWithPic(){
		Account account = getAccountFromSession();
		Weibo weibo = account.getWeibo();
		WeiboUtils.sendWeibo(weibo, weiboDto.getStatus(), weiboDto.getImageUrl());
		return "weibo";
	}
	
	
	private void setAccountToSession(Account account){
		session.setAttribute("account", account);
	}
	private Account getAccountFromSession(){
		Account account = session.getAttribute("account")==null?null:(Account)session.getAttribute("account");
		return account;
	}
	
	
	public void setServletRequest(HttpServletRequest req) {
		this.request = req;
		session = req.getSession();
	}
	
	public void setAccount(Account account) {
		this.account = account;
	}
	public Account getAccount() {
		return account;
	}
	public void setAccountService(AccountService accountService) {
		this.accountService = accountService;
	}
	public AccountService getAccountService() {
		return accountService;
	}

	public void setServletResponse(HttpServletResponse res) {
		this.response = res;
	}
	public void setVideoService(VideoService videoService) {
		this.videoService = videoService;
	}
	public VideoService getVideoService() {
		return videoService;
	}
	public void setPaging(Paging paging) {
		this.paging = paging;
	}
	public Paging getPaging() {
		return paging;
	}
	public void setVideos(List<Video> videos) {
		this.videos = videos;
	}
	public List<Video> getVideos() {
		return videos;
	}
	public void setWeiboDto(WeiboDto weiboDto) {
		this.weiboDto = weiboDto;
	}
	public WeiboDto getWeiboDto() {
		return weiboDto;
	}

	
}
